<?php
namespace Home\Controller;
use Think\Controller;
class PublicController extends Controller {
    // 用户登录页
    public function index(){
//        $this->display();
        $appid = C("WEB_APPID");

        $redirect_uri = urlencode("https://www.58zltc.com/index.php/Home/Public/wxlogin.html");

        $url = "https://open.weixin.qq.com/connect/qrconnect?appid={$appid}&redirect_uri={$redirect_uri}&response_type=code&scope=snsapi_login";
        $this->assign('url',$url);
        $this->display();
    }
    public function login(){
        $appid = C("WEB_APPID");

        $redirect_uri = urlencode("https://www.58zltc.com/index.php/Home/Public/wxlogin.html");

        $url = "https://open.weixin.qq.com/connect/qrconnect?appid={$appid}&redirect_uri={$redirect_uri}&response_type=code&scope=snsapi_login";
        $this->assign('url',$url);
    	$this->display();
    }

    // 验证用户登录
    public function checklogin(){
    	$model = M("User");
    	
    	$map['tel'] = $_POST['tel'];
    	$map['password'] = md5($_POST['password']);
    	$vo = M("User")->where($map)->find();
        if(isset($vo['status']) && $vo['status'] == 0){
            $this->error("该账号被限制登录！");
        }elseif($vo['status'] == 1){
            session("uid", $vo['uid']);
            session("nickname", $vo['nickname']);
            session("headimgurl", $vo['headimgurl']);

            $this->success("登录成功！", U("Tongcheng/Index/index"));
    	}else{
    		$this->error("你输入的信息有误！");
    	}
    }

    // 退出登录
    public function logout(){
        session(null);
        $this->success('退出登录成功！',"login");
    }


    // 用户注册页
    public function register(){
        if(!session("?openid")){
            $this->error('你访问的页面不存在！');
        }
        if(IS_POST){
            if($_POST['code'] != session("code")){
                $this->error("你输入的验证码有误！");
            }
            if($_POST['tel'] != session('tel')){
                $this->error("你输入的手机号已更改，请重新验证！");
            }
            if($_POST['password'] != $_POST['re_password']){
                $this->error("两次输入的密码不一致！");
            }

            $data['tel'] = session('tel');
            $data['password'] = md5($_POST['password']);
            $data['nickname'] = session("nickname");
            $data['openid'] = session("openid");
            $data['sex'] = session("sex");
            $data['province'] = session("province");
            $data['city'] = session("city");
            $data['country'] = session("country");
            $data['headimgurl'] = session("headimgurl");
            $data['unionid'] = session("unionid");
            $data['max_num'] = 5;
            $data['create_time'] = date("Y-m-d H:i:s");
            if($uid = M("User")->add($data)){
                session("uid",$uid);
                $this->success("绑定成功！", U("Index/index"));
            }else{
                $this->error("网络忙！请稍后再试！");
            }
        }else{
            $this->display();
        }
    }

    public function test(){
        echo "ComponentVerifyTicket是：<br/>";

        $cache = S("component_verify_ticket");
        dump($cache);
    }

    public function notify(){
        $postStr = $GLOBALS ["HTTP_RAW_POST_DATA"];
        // extract post data
        if (! empty ( $postStr )) {
            Vendor('weixinDecrypt.wxBizMsgCrypt');
            $token = C("TOKEN");
            $encodingAesKey = C("ENCODING_AES_KEY");
            $appId = C("OPEN_APPID");
            $pc = new \WXBizMsgCrypt($token, $encodingAesKey, $appId);
            $msg = '';
            $errCode = $pc->decryptMsg($_GET['msg_signature'], $_GET['timestamp'], $_GET['nonce'], $postStr, $msg);
            if ($errCode == 0) {
                // print("解密后: " . $msg . "\n");
                $postObj = simplexml_load_string ( $msg, 'SimpleXMLElement', LIBXML_NOCDATA );
                if($postObj->AppId == $appId && $postObj->InfoType == 'component_verify_ticket'){
                    $component_verify_ticket = (string)$postObj->ComponentVerifyTicket;
                    S("component_verify_ticket", $component_verify_ticket);
                    echo "success";
                }else{
                    echo "error";
                }          
            } else {
                echo "error";
            }
        }else{
            echo "error";
        }
    }

    // 获取手机验证码
    public function get_code(){
        if($_POST['tel']){
            $map['tel'] = $_POST['tel'];
            $map['date'] = date("Y-m-d");
            if(M('SmsLog')->where($map)->count() > 4){
                $this->error('该手机号发送次数已达5次，请明日再试！');
            }

            $code = rand(1000,9999);
            $td = $this->send($_POST['tel'],$code);
            if(!$td['result']['success']){
                $this->error("发送失败，".$td['sub_msg']);
                // echo "发送失败，".$td['sub_msg'];
            }else{
                session("code",$code);
                session("tel",$_POST['tel']);

                $new['code'] = $code;
                $new['tel'] = $_POST['tel'];
                $new['param'] = "{\"code\":\"{$code}\",\"product\":\"手机号绑定\"}";
                $new['date'] = date("Y-m-d");
                M("SmsLog")->add($new);

                $this->success('发送成功，请注意查收！');
            }
        }else{
            $this->error('网络忙！请稍后再试！');
        }
    }

    // public function testSend(){
    //     $out = $this->send("182139673","1234");
    //     dump($out);
    // }

    private function send($phone="18213965331",$code="1234"){
        Vendor('alidayu.TopSdk');
        $appkey = "24591506";
        $secret = "39fcfa3441b43196691584e3dc08d111";
        $c = new \TopClient;
        $c ->appkey = $appkey ;
        $c ->secretKey = $secret ;
        $c ->format = "json";
        $req = new \AlibabaAliqinFcSmsNumSendRequest;
        $req ->setExtend( "" );
        $req ->setSmsType( "normal" );
        $req ->setSmsFreeSignName( "  " );
        $req ->setSmsParam("{\"code\":\"{$code}\",\"product\":\"手机号绑定\"}");
        $req ->setRecNum( "{$phone}" );
        $req ->setSmsTemplateCode( "SMS_16340266" );
        $resp = $c ->execute( $req );
        // $td = simplexml_load_string($resp, 'SimpleXMLElement', LIBXML_NOCDATA);
        $json = json_encode($resp);
        $td = json_decode($json,true);
        // dump($resp);
        // dump($td);
        return $td;
        // dump($td);

    }


    public function wxlogin(){
        if(!isset($_GET['code'])){
            $this->error('授权失败！请重试！', "login");
        }
        $appid = C("WEB_APPID");
        $appsecret = C("WEB_APPSECRET");
        $json = $this->ihttp("https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$appsecret}&code={$_GET['code']}&grant_type=authorization_code");
        $td = json_decode($json, true);
        if(!$td['openid']){
            $this->error('授权失败！请重试！', "login");
        }

        $info_json = $this->ihttp("https://api.weixin.qq.com/sns/userinfo?access_token={$td['access_token']}&openid={$td['openid']}");
        $info = json_decode($info_json, true);
        if($info['errcode']){
            $this->error('授权失败！请重试！', "login");
        }
        session("nickname", $info['nickname']);
        session("openid", $info['openid']);
        session("sex", $info['sex']);
        session("province", $info['province']);
        session("city", $info['city']);
        session("country", $info['country']);
        session("headimgurl", $info['headimgurl']);
        session("unionid", $info['unionid']);

        $map['openid'] = $info['openid'];
        $uid = M("User")->where($map)->getField("uid");

        $vo = M("User")->where($map)->find();
        if(isset($vo['status']) && $vo['status'] == 0){
            $this->error("该账号被限制登录！");
        }elseif($vo['status'] == 1){
            session("uid", $vo['uid']);
            session("nickname", $vo['nickname']);
            session("headimgurl", $vo['headimgurl']);

            $this->success("登录成功！", U("Index/index"));
        }else{
            $this->success("请先绑定手机号！", "register");
        }
    }

    private function ihttp($url){
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $out = curl_exec($ch);
        curl_close($ch);
        return $out;
    }

    public function upload(){
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize   =     3145728 ;// 设置附件上传大小
        $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $upload->rootPath  =      './Uploads/'; // 设置附件上传根目录
        $upload->savePath  =      ''; // 设置附件上传（子）目录
        // 上传文件 
        $info   =   $upload->upload();
        if(!$info) {// 上传错误提示错误信息
            $arr = array("err_code"=>400,"err_msg"=>$upload->getError());
            $this->ajaxReturn($arr);
        }else{// 上传成功 获取上传文件信息
            $file = $info['file'];
            $arr = array("err_code"=>0,"file_name"=>$file['savepath'].$file['savename']);
            $this->ajaxReturn($arr);
        }
    }
    // 用于富文本调用的图片上传接口
    public function upload1(){
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize   =     3145728 ;// 设置附件上传大小
        $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $upload->rootPath  =      './Uploads/'; // 设置附件上传根目录
        $upload->savePath  =      ''; // 设置附件上传（子）目录
        // 上传文件 
        $info   =   $upload->upload();
        if(!$info) {// 上传错误提示错误信息
            $arr = array("code"=>400,"msg"=>$upload->getError());
            $this->ajaxReturn($arr);
        }else{// 上传成功 获取上传文件信息
            $file = $info['file'];
            $arr = array("code"=>0, "data"=>array("src"=>"../../../Uploads/".$file['savepath'].$file['savename']));
            $this->ajaxReturn($arr);
        }
    }
}